package cn.edu.aust.myexpri5app.UI;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.apkfuns.logutils.LogUtils;

import org.apache.commons.lang3.StringUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cn.edu.aust.myexpri5app.MainActivity;
import cn.edu.aust.myexpri5app.R;
import cn.edu.aust.myexpri5app.model.UserInfo;
import cn.edu.aust.myexpri5app.utils.FileTools;
import cn.edu.aust.myexpri5app.utils.JsonTools;


public class RegisterActivity extends AppCompatActivity {
    @BindView(R.id.et_username)
    EditText etUsername;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.et_pass_second)
    EditText etPassSecond;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.rb_male)
    RadioButton rbMale;
    @BindView(R.id.rb_female)
    RadioButton rbFemale;
    @BindView(R.id.cb_shuttlecock)
    CheckBox cbShuttlecock;
    @BindView(R.id.cb_basketball)
    CheckBox cbBasketball;
    @BindView(R.id.cb_music)
    CheckBox cbMusic;
    @BindView(R.id.cb_reading)
    CheckBox cbReading;
    @BindView(R.id.cb_swing)
    CheckBox cbSwing;
    @BindView(R.id.cb_sing)
    CheckBox cbSing;
    @BindView(R.id.btn_cancel)
    Button btnCancel;
    @BindView(R.id.btn_okInner)
    Button btnOkInner;
    @BindView(R.id.btn_okOuter)
    Button btnOkOuter;

    private String sex,hobbys="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        String username=getIntent().getStringExtra("username");

        ButterKnife.bind(this);
//        btnCancel.setOnClickListener(listener);
//        btnOkInner.setOnClickListener(listener);
//        btnOkOuter.setOnClickListener(listener);
        etUsername.setText(username);
    }

    //函数格式有所变化
    @OnCheckedChanged({R.id.rb_male,R.id.rb_female})
    public void onRadioChechedChanged(CompoundButton buttonView, boolean isChecked){
        switch (buttonView.getId()){
            case R.id.rb_male:
                if (isChecked){
                    sex="male";
                }
                break;
            case R.id.rb_female:
                if (isChecked){
                    sex="female";
                }
                break;
            default:
                sex="";
        }
    }
    /*
    @OnCheckedChanged(R.id.rg_sex)
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId==R.id.rb_male){
            sex="male";
        }else if (checkedId==R.id.rb_female){
            sex="female";
        }else{
            sex="";
        }
        Toast.makeText(getApplicationContext(),"您选择的性别是："+sex,Toast.LENGTH_LONG).show();
        Log.i("user_sex",sex);
    }*/
    @OnTextChanged(value = R.id.et_pass_second, callback = OnTextChanged.Callback.BEFORE_TEXT_CHANGED)
    void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @OnTextChanged(value = R.id.et_pass_second, callback = OnTextChanged.Callback.TEXT_CHANGED)
    void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @OnTextChanged(value =R.id.et_pass_second, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void afterTextChanged(Editable s) {
        String ps=etPassword.getText().toString().trim();
        if (!s.toString().isEmpty() && !ps.startsWith(s.toString())){
            Toast.makeText(RegisterActivity.this,"两次输入密码不一致！请重新输入！",Toast.LENGTH_LONG).show();;
        }
    }

    @OnCheckedChanged({ R.id.cb_shuttlecock,R.id.cb_basketball,R.id.cb_music,
            R.id.cb_reading,R.id.cb_swing,R.id.cb_sing })
    void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        String motion=buttonView.getText().toString();
        if (isChecked){
            if (!hobbys.contains(motion)){
                Log.i("hobbys_before",hobbys);
                hobbys= StringUtils.strip(hobbys+" "+motion);
                Log.i("hobby_len", StringUtils.length(hobbys)+"");
                Log.i("hobbys_after",hobbys);
            }
        }else{
            if (hobbys.contains(motion)){
                Log.i("hobbys_before",hobbys);
                int index=hobbys.indexOf(motion)+StringUtils.length(motion);
                if (index==StringUtils.length(hobbys)){//是否是最后一个
                    hobbys=hobbys.replace(motion,"");
                }else{
                    hobbys=hobbys.replace(motion+" ","");
                }
                Log.i("hobbys_after",hobbys);
            }
        }
    }

    @OnClick({ R.id.btn_okInner, R.id.btn_okOuter, R.id.btn_cancel })
    void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_cancel:
                finish();
                break;
            case R.id.btn_okInner:
                if (etUsername.getText().toString().trim().equals("")){
                    Toast.makeText(getApplicationContext(),"用户名不能为空",Toast.LENGTH_LONG).show();
                    return;
                }else{
                    //读取文件内容
                    List<UserInfo> userList= null;
                    try {
                        String origData=FileTools.readDataFromInner(getApplicationContext());
                        userList = JsonTools.jsonToObjs(origData);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    LogUtils.d("username: "+etUsername.getText().toString());
                    if(userList!=null && !userList.isEmpty()){
                        for (UserInfo u:userList){
                            if (StringUtils.equals(u.getUsername().trim(),etUsername.getText().toString().trim())){
                                Toast.makeText(getApplicationContext(),"该用户已存在",Toast.LENGTH_LONG).show();
                                finish();
                            }
                        }
                    }else{
                        userList=new ArrayList<>();
                    }

                    UserInfo user=new UserInfo();
                    String userId= UUID.randomUUID().toString().replace("-","");
                    user.setId(userId);
                    user.setUsername(etUsername.getText().toString());
                    user.setPassword(etPassword.getText().toString());
                    user.setPhone(etPhone.getText().toString());
                    user.setSex(sex);
                    ArrayList<String> hobList=null;
                    if (hobbys!=null && !hobbys.equals("")){
                          hobList=new ArrayList<>();
                          String[] hobs=StringUtils.split(hobbys," ");
                          for (String hob:hobs){
                              hobList.add(hob);
                          }
                    }
                    user.setHobbys(hobList);
                    userList.add(user);

                    //转换成JSON串
                    String jsonStr=JsonTools.objsToJson(userList);
                    LogUtils.d(jsonStr+"");
                    //写入文件
                    FileTools.writeDataToInner(getApplicationContext(),jsonStr);
                    LogUtils.d("文件写入成功！");
                    Toast.makeText(getApplicationContext(),"数据写入成功！",Toast.LENGTH_LONG).show();
                    startActivity(new Intent(RegisterActivity.this,MainActivity.class));
                }
                break;
            case R.id.btn_okOuter:
                if (etUsername.getText().toString().equals("")){
                    Toast.makeText(getApplicationContext(),"用户名不能为空",Toast.LENGTH_LONG).show();
                    return;
                }
                break;
        }
    }
}
